(function (window) {
    //防止重复加载
    var md5 = typeof require !== 'undefined' ? require('./libs/md5') : window.md5;
    var fp = typeof require !== 'undefined' ? require('./libs/fp') : window._fp;
    //sdk全局对象
    var jsBridge = {};
    var VERSION = '1.0.0.0';//sdk版本号
    //全局默认配置
    var globalObject = {
        "env": "dev",
        "aid": "",
        "t4": new Date().getTime(),
        "mm": "1",
        "toUrl": ""
    };
    //工具函数
    var util = {
        /*
         * 过滤文本中的任何空白字符，包括空格、制表符、换页符等等。等价于[ \f\n\r\t\v]。
         * */
        trim: function (str) {
            return str.replace(/\s/g, '');
        },
        /**
         * @desc  获取随机固定位数的随机字符串
         * @param length {Number} 返回的随机字符串位数
         * @return {String} 随机字符串
         */
        generateMixed: function (length) {
            var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
            var res = "";
            for (var i = 0; i < length; i++) {
                var id = Math.ceil(Math.random() * 35);
                res += chars[id];
            }
            return res;
        },
        queryString: function () {
            // This function is anonymous, is executed immediately and
            // the return value is assigned to QueryString!
            var query_string = {};
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                // If first entry with this name
                if (typeof query_string[pair[0]] === "undefined") {
                    query_string[pair[0]] = decodeURIComponent(pair[1]);
                    // If second entry with this name
                } else if (typeof query_string[pair[0]] === "string") {
                    query_string[pair[0]] = [query_string[pair[0]], decodeURIComponent(pair[1])];
                    // If third or later entry with this name
                } else {
                    query_string[pair[0]].push(decodeURIComponent(pair[1]));
                }
            }
            return query_string;
        },

        extend: function (obja, objb) {
            if (!this.isObject(obja)) {
                return objb;
            } else if (!this.isObject(objb)) {
                return obja;
            } else {
                for (var i in objb) {
                    if (objb.hasOwnProperty(i)) {
                        if (objb[i] === undefined) continue;
                        obja[i] = objb[i];
                    }
                }
                return obja;
            }
        },
        isObject: function (val) {
            return val.constructor === Object
        },
        /*
         *过滤url中的协议
         * */
        encodeURIExceptProtocol: function (url) {
            var len = 0;
            if (url.search(/^https/) !== -1) {
                len = 8;
            } else if (url.search(/^http/) !== -1) {
                len = 7;
            }
            return encodeURIComponent(url.slice(len));
        },
        /*
         * 获取指定字段的配置
         * */
        getConfig: function (key) {
            if (!key) return '';
            return clientOptions[key] || globalObject[key] || ''
        }
    };

    /*
     *  initialize globalObject
     */
    globalObject = util.extend(globalObject, getEjsObject());

    // api接口 分别对应https or http
    var reportApi = ('https:' === document.location.protocol ? 'https://sdkstatic.51kupai.com/' : 'http://sdkstatic.hiwemeet.com/');
    // 开发环境设置
    var envConfig = {
        dev: {
            debug: true,
            api: reportApi + 'sdkoff'
        },
        prd: {
            debug: false,
            api: reportApi + 'sdkon'
        }
    };
    // 本地存储读写
    var localstorage = {
        //设备id
        set: function () {
            var cy_aidsdk_mapping = {};

            if(!window.localStorage.getItem('cy_aidsdk_co')){
                var exp = new Date();
                var random = util.generateMixed(6);
                window.localStorage.setItem('cy_aidsdk_co', (exp.getTime() + '_' + random));
            }
            var co = window.localStorage.getItem('cy_aidsdk_co');
            var ss = md5(globalObject.aid + '_' + co + '_' + globalObject.t4);
            cy_aidsdk_mapping.aid = globalObject.aid;
            cy_aidsdk_mapping.ss = ss;
            cy_aidsdk_mapping.va = md5(fp);
            cy_aidsdk_mapping.co = co;
            cy_aidsdk_mapping.mm = globalObject.mm;
            window.localStorage.setItem('cy_aidsdk_mapping', JSON.stringify(cy_aidsdk_mapping));
            return cy_aidsdk_mapping;
        },
        get: function () {
            return window.localStorage.getItem('cy_aidsdk_mapping');
        },
        remove: function () {
            window.localStorage.removeItem('cy_aidsdk_mapping');
        },
        isLsExisted: function () {
            var val = this.get('cy_aidsdk_mapping');
            var ret = false;
            if (val !== null) {
                ret = true;
            }
            return ret;
        }
    };

    // event listener function
    var eventListener = {
        /**
         * @desc add listener IE and chrome
         * @param node {Object} document node element
         * @param type {String} event type name
         * @param handler {Function} callback method
         * @return {Boolean} true or false
         */
        addEvent: function (node, type, handler) {
            if (!node) return false;
            if (node.addEventListener) {
                node.addEventListener(type, handler, false); // 所有主流浏览器，除了 IE 8 及更早 IE版本
                return true;
            }
            else if (node.attachEvent) {
                node['e' + type + handler] = handler;
                node[type + handler] = function () {
                    node['e' + type + handler](window.event);
                };
                node.attachEvent('on' + type, node[type + handler]); // IE 8 及更早 IE 版本
                return true;
            }
            return false;
        },
        /**
         * @desc remove listener IE and chrome
         * @param node {Object} document node element
         * @param type {String} event type name
         * @param handler {Function} callback method
         * @return {Boolean} true or false
         */
        removeEvent: function (node, type, handler) {
            if (!node) return false;
            if (node.removeEventListener) {
                node.removeEventListener(type, handler, false);
                return true;
            }
            else if (node.detachEvent) {
                node.detachEvent('on' + type, node[type + handler]);
                node[type + handler] = null;
            }
            return false;
        },
        /**
         * @desc mobile touch event
         * @param obj {Object} document node element
         * @param type {String} event type name
         * @param func {Function} callback method
         * @return void
         */
        touchEvent: function (obj, type, func) {
            //滑动范围在5x5内则做点击处理，s是开始，e是结束
            var init = {x: 5, y: 5, sx: 0, sy: 0, ex: 0, ey: 0};
            var sTime = 0, eTime = 0;
            type = type.toLowerCase();

            obj.addEventListener("touchstart", function () {
                sTime = new Date().getTime();
                init.sx = event.targetTouches[0].pageX;
                init.sy = event.targetTouches[0].pageY;
                init.ex = init.sx;
                init.ey = init.sy;
                if (type.indexOf("start") !== -1) func();
            }, false);

            obj.addEventListener("touchmove", function () {
                event.preventDefault();//阻止触摸时浏览器的缩放、滚动条滚动
                init.ex = event.targetTouches[0].pageX;
                init.ey = event.targetTouches[0].pageY;
                if (type.indexOf("move") !== -1) func();
            }, false);

            obj.addEventListener("touchend", function () {
                var changeX = init.sx - init.ex;
                var changeY = init.sy - init.ey;
                if (Math.abs(changeX) > Math.abs(changeY) && Math.abs(changeY) > init.y) {
                    //左右事件
                    if (changeX > 0) {
                        if (type.indexOf("left") !== -1) func();
                    } else {
                        if (type.indexOf("right") !== -1) func();
                    }
                }
                else if (Math.abs(changeY) > Math.abs(changeX) && Math.abs(changeX) > init.x) {
                    //上下事件
                    if (changeY > 0) {
                        if (type.indexOf("top") !== -1) func();
                    } else {
                        if (type.indexOf("down") !== -1) func();
                    }
                }
                else if (Math.abs(changeX) < init.x && Math.abs(changeY) < init.y) {
                    eTime = new Date().getTime();
                    //点击事件，此处根据时间差细分下
                    if ((eTime - sTime) > 300) {
                        if (type.indexOf("long") !== -1) func(); //长按
                    }
                    else {
                        if (type.indexOf("click") !== -1) func(); //当点击处理
                    }
                }
                if (type.indexOf("end") !== -1) func();
            }, false);
        }
    };
    //JS http ajax request
    var httpRequest = {
        ajax: function (type, url, data, success, failed) {
            // 创建ajax对象
            var xhr = null;
            if (window.XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            } else {
                xhr = new ActiveXObject('Microsoft.XMLHTTP');
            }

            type = type.toUpperCase();
            // 用于清除缓存
            var random = Math.random();

            if (typeof data === 'object') {
                var str = '';
                for (var key in data) {
                    str += key + '=' + data[key] + '&';
                }
                data = str.replace(/&$/, '');
            }

            if (type === 'GET') {
                if (data) {
                    xhr.open('GET', url + '?' + data, true);
                } else {
                    xhr.open('GET', url + '?t=' + random, true);
                }
                xhr.send();

            } else if (type === 'POST') {
                xhr.open('POST', url, true);//异步：true 同步：false;
                // xhr.setRequestHeader("Accept-Encoding-SDK", "sdk_gzip");
                // xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xhr.send(data);
                // xhr.send(pako.gzip(data));
            }

            // 处理返回数据
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        success(xhr.responseText);
                    } else {
                        if (failed) {
                            failed(xhr.status);
                        }
                    }
                }
            }
        }
    };

    //获取当前点击时间
    var dateTime = {
        formatTime: function () {
            Date.prototype.Format = function (fmt) {
                var o = {
                    "M+": this.getMonth() + 1, //月份
                    "d+": this.getDate(), //日
                    "h+": this.getHours(), //小时
                    "m+": this.getMinutes(), //分
                    "s+": this.getSeconds(), //秒
                    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                    "S": this.getMilliseconds() //毫秒
                };
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                for (var k in o)
                    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                return fmt;
            };

            return new Date().Format("yyyy-MM-dd hh:mm:ss");
        },
        unixTime: function () {
            return new Date().getTime();
        }
    };

    // 设备操作系统判断
    var deviceDetector = {
        //判断当前浏览器的类型
        browser: function () {
            var OsObject = {};
            if (navigator.userAgent.match(/MicroMessenger/i) === "micromessenger") {
                return {browser: 'weixin'};
            } else if (navigator.userAgent.indexOf("Chrome") > 0) {
                if (navigator.userAgent.indexOf("OPR/") > 0) {
                    OsObject = {browser: 'Opera'};
                } else if (navigator.userAgent.indexOf("BIDUBrowser") > 0) {
                    OsObject = {browser: 'baidu'};
                } else if (navigator.userAgent.indexOf("UBrowser") > 0) {
                    OsObject = {browser: 'UC'};
                } else if (navigator.userAgent.indexOf("QQBrowser") > 0) {
                    OsObject = {browser: 'QQBrowser'};
                } else if (navigator.userAgent.indexOf("2345Explorer") > 0) {
                    OsObject = {browser: '2345Explorer'};
                } else {
                    OsObject = {browser: 'Chrome'};
                }
            } else if (navigator.userAgent.indexOf("Safari") > 0) {
                return {browser: 'safari'};
            } else {
                return {browser: 'else'};
            }
            return OsObject;
        },
        os: function () {
            var osData = {};
            var sUserAgent = navigator.userAgent;
            var isWin = (navigator.platform === "Win32") || (navigator.platform === "Windows");
            var isMac = (navigator.platform === "Mac68K") || (navigator.platform === "MacPPC") || (navigator.platform === "Macintosh") || (navigator.platform === "MacIntel");
            if (isMac) {
                osData.os = 'macOS';
            }
            var isUnix = (navigator.platform === "X11") && !isWin && !isMac;
            if (isUnix) {
                osData.os = 'Unix';
            }
            var isLinux = (String(navigator.platform).indexOf("Linux") > -1);
            if (isLinux) {
                osData.os = 'Linux';
            }
            if (isWin) {
                var isWin2K = sUserAgent.indexOf("Windows NT 5.0") > -1 || sUserAgent.indexOf("Windows 2000") > -1;
                if (isWin2K) {
                    osData.os = 'Win2000';
                }
                var isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1 || sUserAgent.indexOf("Windows XP") > -1;
                if (isWinXP) {
                    osData.os = 'WinXP';
                }
                var isWin2003 = sUserAgent.indexOf("Windows NT 5.2") > -1 || sUserAgent.indexOf("Windows 2003") > -1;
                if (isWin2003) {
                    osData.os = 'Win2003';
                }
                var isWinVista = sUserAgent.indexOf("Windows NT 6.0") > -1 || sUserAgent.indexOf("Windows Vista") > -1;
                if (isWinVista) {
                    osData.os = 'WinVista';
                }
                var isWin7 = sUserAgent.indexOf("Windows NT 6.1") > -1 || sUserAgent.indexOf("Windows 7") > -1;
                if (isWin7) {
                    osData.os = 'Win7';
                }
                var isWin8 = sUserAgent.indexOf("Windows NT 8.1") > -1 || sUserAgent.indexOf("Windows 8") > -1;
                if (isWin8) {
                    osData.os = 'Win8';
                }
                var isWin10 = sUserAgent.indexOf("Windows NT 10.0") > -1 || sUserAgent.indexOf("Windows 10") > -1;
                if (isWin10) {
                    osData.os = 'Win10';
                }
            }
            if (sUserAgent.indexOf('Android') > -1 || sUserAgent.indexOf('Linux') > -1) {//安卓手机
                osData.os = 'Android';
            } else if (sUserAgent.indexOf('iPhone') > -1 || sUserAgent.indexOf('iPad') > -1) {//苹果手机
                osData.os = 'iOS';
            } else if (sUserAgent.indexOf('Windows Phone') > -1) {//winphone手机
                osData.os = 'winPhone';
            }
            return osData;
        }
    };

    function getEjsObject() {
        var ret = {};
        var _ejs = window._ajs;
        for (var i = 0; i < _ejs.length; i++) {
            var key = _ejs[i][0];
            var value = _ejs[i][1];
            if (key.toLowerCase() === 'env') {
                if (value.toString() === 'true' || value.toString() === 'dev') {
                    ret['env'] = 'dev';
                } else {
                    ret['env'] = 'prd';
                }
                continue;
            } else if (key.toLowerCase() === 'platform' && value !== 'client') {
                continue;
            }
            ret[key] = _ejs[i][1];
        }
        return ret;
    }

    function sendHttpRequest(dataObj,success,fail) {
        var onSuccess = function (status) {
            success?success(status):null;
        };
        var onFailure = function (status) {
            fail?fail(status):null;
        };
        httpRequest.ajax('post', envConfig[globalObject.env].api, JSON.stringify(dataObj), onSuccess, onFailure);
    }

    function sendPagepath(){
        var aidObj = localstorage.set();
        var dataObj = {
            "aidvlog" : [{
                "aid":aidObj.aid || 'null',//	广告ID
                "co": aidObj.co,//设备ID
                "g" : deviceDetector.os().os || 'null',//操作系统
                "ss":aidObj.ss || 'null',//safari标记
                "t4":globalObject.t4 || 'null',//中间页加载时间
                "va":aidObj.va || 'null',//画布信息
                "mm":deviceDetector.os().os === 'Android' ? '2' : globalObject.mm,
                "i":(window.screen.width*devicePixelRatio + 'x' + window.screen.height*devicePixelRatio) || 'null'	//屏幕分辨率
            }]
        };
        sendHttpRequest(dataObj);

        setTimeout(function () {
            if(globalObject.toUrl)
                window.location.href = globalObject.toUrl;
        },300);
    }
    function init() {
        //精确匹配
        if (globalObject.mm.toString() !== '2' && deviceDetector.os().os.toLowerCase() === 'ios') {
            var browser = deviceDetector.browser().browser;
            if (browser === 'weixin') {
                document.body.style.display = 'block';
                return false;
            } else if (browser === 'safari') {
                sendPagepath();
            } else {
                document.body.style.display = 'block';
                return false;
            }
        } else {
            //模糊匹配
            sendPagepath();
        }
    }

    window.Aidsdk = jsBridge;
    //客户端自动注入，客户端调用初始化
    eventListener.addEvent(window, 'load', init);
})(window);